import { ref, onMounted } from "vue";
import { handleTree } from "@/utils/tree";
import { getMenuList } from "@/api/system";

export function useMenu() {
  const dataList = ref([]);
  const loading = ref(true);

  const columns: TableColumnList = [
    {
      label: "菜单名称",
      align: "left",
      width: 120,
      prop: "name"
    },
    {
      label: "菜单ID",
      width: 80,
      prop: "id"
    },
    {
      label: "菜单类型",
      width: 70,
      prop: "type",
      cellRenderer: ({ row }) => (
        <el-tag type={row.type == "menu" ? "success" : "primary"}>
          {row.type == "menu" ? "菜单" : "页面"}
        </el-tag>
      )
    },
    {
      label: "路由",
      prop: "route_url"
    },
    {
      label: "图标",
      width: 120,
      slot: "route_icon"
    },
    {
      label: "排序",
      width: 80,
      prop: "sort"
    },
    {
      label: "操作",
      fixed: "right",
      width: 310,
      slot: "operation"
    }
  ];

  function loadData() {
    return new Promise((resolve, reject) => {
      getMenuList()
        .then(res => {
          const data = res.data;
          dataList.value = handleTree(data, "id", "p_id");
          loading.value = false;
          resolve(res.data);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  onMounted(() => {
    loadData();
  });

  const formPermsColumns: TableColumnList = [
    {
      label: "权限名称",
      prop: "title",
      cellRenderer: ({ row }) => <el-input v-model={row.title} />
    },
    {
      label: "权限Code",
      prop: "code",
      cellRenderer: ({ row }) => <el-input v-model={row.code} />
    },
    {
      label: "删除",
      slot: "operation"
    }
  ];

  return {
    formPermsColumns,
    columns,
    dataList,
    loading,
    loadData
  };
}
